#coding=utf-8
import thread,time
from sdsource.web.utility import get_soup
from sdsource.exception import NoPriceError
from sdsource.models import RTPrice
from sdsource.web.sina.suggest import query

url = "http://hq.sinajs.cn/list=%s"
def get_market(code):
    return query(code)[0].market

def get_p_by_row(row):
    
    import datetime as dt
    now = dt.datetime.now().isoformat()
    
    s = row
    
    i = s.find('=')
    code = s[i-6: i]
    rp = RTPrice(code)
    
    try:
        start = s.find('"') + 1    
        s = s[start:]
        end = s.find('"')  
        s = s[:end]
        
        data = s.split(',')[1:]
       
        rp.open = float( data[0] )
        rp.now = float( data[2] )
        
        pre_close = float(data[1])
        rp.change = (rp.now - pre_close)/pre_close *100
        rp.jump = (rp.open - pre_close)/pre_close *100
        
        rp.highest = float( data[3] )
        rp.lowest = float( data[4] )
        rp.bid_buy = float( data[5] )
        rp.bid_sell = float( data[6] )
        rp.volume = int( data[7] )
        rp.amount = int( float(data[8]) )
        
        if rp.amount == 0:return None
        
        for i in range(0, 10, 2):
            rp.slot_buy.append([ float(data[10+i]), int(data[9+i])])
            rp.slot_sell.append([ float(data[20+i]),int(data[19+i])])
            
        rp.date = data[-2]
        rp.time = data[-1]
    
    except:
        raise NoPriceError(code, now)
    return rp
            
def get_rtprice(code, mcode=False):
    if not mcode:
        u = url%(get_market(code)+code)
    else:
        u = url%code
        
    soup = get_soup(u)
    s = str(soup)
    
    try:
        data = get_p_by_row(s)
    except NoPriceError:
        return None     
    return data
    
def get_rtprices(codes):
    n = len(codes)/100 + 1
    rs = []
    
    for i in range(n):
        cs = codes[i*100: (i+1)*100]
        
        u = []
        for c in cs:
            u.append("%s%s"%(get_market(c), c) )
        u = ','.join(u)    
        
        soup = get_soup(url%u, is_cached=False)
        ss = str(soup).strip()
         
        for s in ss.split(';')[:-1]:
            s = s.strip()
            try:
                data = get_p_by_row(s)
            except NoPriceError, e:
                print e
            else:
                if data:rs.append(data)
    return rs    

def get_rps(id_, is_alive, cs, rps, lock,):
    #print 'Thread %i starts.'%id_
    #print len(cs)
    rs, u2 = [], []
    for c in cs:
        #print c
        u2.append( "%s%s"%(get_market(c), c) )
        u = ','.join(u2)    
        
    soup = get_soup(url%u)
    ss = str(soup).strip()
        
    for s in ss.split(';')[:-1]:
        s = s.strip()
        try:
            data = get_p_by_row(s)
        except NoPriceError, e:
            print e
        else:
            if data:rs.append(data)
            
    #print len(rs)        
    lock.acquire()
    rps.extend(rs)
    lock.release()
    
    is_alive[id_] = False
    
    #print 'Thread %i finished.'%id_
    
def get_rtprices2(codes, n=10):
    '''使用了线程'''
    
    per_time = 100
    
    rps = []
    lock = thread.allocate_lock()
    
    while True:
        if not codes:return rps
        
        ntimes = per_time * n
        cs , codes = codes[:ntimes], codes[ntimes:]
        
        a,b = len(cs)/per_time, len(cs)%per_time
        if b == 0: n2 = a
        else:
            n2 = a + 1
        
        #print n2
        is_alive = [True for i in range(n2)]
        
        for i in range(n2):
            
            cs2 = cs[i*per_time: (i+1)*per_time]            
            thread.start_new(get_rps, (i, is_alive, cs2, rps, lock))
            time.sleep(1)
            
        while True:
            time.sleep(0.5)
            if not reduce(lambda x, y : x or y, is_alive):
                break
                
